package gui;
/**
 * 
 * task controller class- 
 * ables a task to be paused, stopped or continue safetly
 *
 */
public class TaskController {
	Runnable r;
	Thread t;
	Object lock;
	boolean stop,pause;
	
	
	/**
	 * myTask is the task the big class holds and it implements all the methods 
	 * of stop, pause and continue
	 */
	private class MyTask implements Runnable{
		public void run(){
			//as long as not stopped - run safe
			synchronized (lock) {
				while(!stop){
					if(pause)
					  try {
						lock.wait();
					  } catch (InterruptedException e) {}
					r.run();
				}
			}
		}
	}
	
	/**
	 * c'tor- gets a runnable, and creates a lock 
	 * @param r
	 */
	public TaskController(Runnable r) {
		this.r=r;
		lock=new Object();
	}
	
	/**
	 * start- start the task with a thread
	 */
	public void start(){
		pause=false;
		stop=false;
		new Thread(new MyTask()).start();
	}
	
	/**
	 * set the pause member to true, in order to stop
	 */
	public void pause(){
		pause=true;
	}
	
	/**
	 * cont- continue the task, important to be thread safe
	 */
	public void cont(){
		pause=false;
		synchronized (lock) {
			lock.notify();
		}
	}

	/**
	 * sets the stop to true in order to stop
	 */
	public void stop() {
		stop=true;
	}
}


